/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package YottaTron.communication;

import YottaTron.*;
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class CommunicationTCP extends Thread {

    static final int ACCEPT = 0;
    static final int NICK = 1;
    static final int SIGN = 1;
    static final int UNSIGN = 2;
    static final int MSG = 3;

    private Socket sock;
    private PrintWriter out;  // output to the server
    BufferedReader in;
    ChatGui gui;

    InetSocketAddress serverAddress;
    String host;
    int port;

    public CommunicationTCP(String host, int port, ChatGui gui) // contact the server and start a ChatWatcher thread
    {
        this.gui = gui;
        //connectToServer(host, port);
        this.host = host;
        this.port = port;
        serverAddress = new InetSocketAddress(host, port);

        connectToServer();
        sendNick(gui.tfNick.getText());
        this.start();
    }

    public void connectToServer() {
        try {
            sock = new Socket(host, port);
            sock.setTcpNoDelay(true);//tcp packet nebude cekat na dalsi data a rovnou se odesle
            System.out.println("tcp nodelay    " + sock.getTcpNoDelay());
            in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            out = new PrintWriter(sock.getOutputStream(), true);  // autoflush

            this.start();    // start watching for server msgs
        } catch (Exception e) {
            System.out.println(e);
            gui.taChat.append(e.toString());
        }
    //sendNick(gui.tfNick.getText());
    }

    public void sendNick(String nick) {
        if (out != null) {
            out.println(NICK);
            out.println(nick);
        }
    }

    @Override
    public void run() /* Read a server message, display it, repeat.*/ {
        String line;
        try {

            while ((line = in.readLine()) != null) {
                System.out.println("line " + line);
                gui.taChat.append(line + "\n");
                gui.taChat.setCaretPosition(gui.taChat.getText().length());
            }

        } catch (Exception e) // socket closure will cause termination of while
        {
            System.out.println(e);
            JOptionPane.showMessageDialog(null, "Link to Server Lost!", "Connection Closed", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    } // end of run()

    public void sendMessage(String msg) /* Check if the user has supplied a message, then
    send it to the server. */ {
        if (msg.equals("")) {
            JOptionPane.showMessageDialog(null,
                    "No message entered", "Send Message Error",
                    JOptionPane.ERROR_MESSAGE);
        } else {
            gui.taChat.append(sock.getInetAddress().toString() + "");
            out.println(MSG);
            out.println(msg);
        // showMsg("Sent: " + msg + "\n");
        }
    }  // end of sendMessage()

    private void closeLink() {
        try {
            out.println("bye");    // tell server that client is disconnecting
            sock.close();
        } catch (Exception e) {
            System.out.println(e);
        }

        System.exit(0);
    } // end of closeLink()
}
